import Foundation

class NetworkUtil {
    
    // 定义请求结果回调类型
    typealias CompletionHandler = (Result<Data, Error>) -> Void
    
    // 单例模式
    static let shared = NetworkUtil()
    private init() {}
    
    // 发送 GET 请求
    func getRequest(urlString: String, completion: @escaping CompletionHandler) {
        guard let url = URL(string: urlString) else {
            completion(.failure(NetworkError.invalidURL))
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let data = data else {
                completion(.failure(NetworkError.noData))
                return
            }
            
            completion(.success(data))
        }
        
        task.resume()
    }
    
   
    func postRequest(urlString: String, parameters: String, completion: @escaping CompletionHandler) {
        guard let url = URL(string: urlString) else {
            completion(.failure(NetworkError.invalidURL))
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = parameters.data(using: .utf8)
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let data = data else {
                completion(.failure(NetworkError.noData))
                return
            }
            
            completion(.success(data))
        }
        
        task.resume()
    }
    
    // 自定义网络错误类型
    enum NetworkError: Error {
        case invalidURL
        case noData
    }
    
   
    
}


